package com.novel.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.novel.common.exception.CustomerException;
import com.novel.mapper.OrderMapper;
import com.novel.mapper.UserMapper;
import com.novel.pojo.system.Order;
import com.novel.pojo.system.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@Service
public class OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    /**
     * 用户分页查询订单信息
     */
    public PageInfo<Order> queryOrderByUserAndPage(String userId, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);

        Example example = new Example(Order.class);
        example.setOrderByClause("created_time desc");
        example.createCriteria().andEqualTo("userId", userId);
        List<Order> orderList = orderMapper.selectByExample(example);

        return new PageInfo<>(orderList);
    }

    /**
     * 管理员分页查询订单信息
     */
    public PageInfo<Order> queryOrderByPage(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);

        Example example = new Example(Order.class);
        example.setOrderByClause("created_time desc");
        List<Order> orderList = orderMapper.selectByExample(example);

        return new PageInfo<>(orderList);
    }

    /**
     * 取消订单
     */
    @Transactional
    public boolean cancelOrderByOrderNo(String orderNo) {

        Order record = new Order();
        record.setOrderNo(orderNo);

        Order orderInfo = orderMapper.selectOne(record);
        orderInfo.setStatus(-1);

        return orderMapper.updateByPrimaryKey(orderInfo) == 1;
    }


    /**
     * 创建订单，生成订单信息
     */
    @Transactional
    public boolean createdOrder(Order order) {
        return orderMapper.insert(order) == 1;
    }


    /**
     * 订单支付
     * 1.扣掉用户的钱
     * 2.给用户增加虚拟币
     * 3.订单状态变化
     */
    @Transactional
    public boolean payOrder(String orderNo) {
        //查询订单信息
        Order record = new Order();
        record.setOrderNo(orderNo);
        Order orderInfo = orderMapper.selectOne(record);
        //查询用户信息
        User userInfo = userMapper.selectByPrimaryKey(orderInfo.getUserId());
        //增加虚拟币
        userInfo.setAmount(userInfo.getAmount() + orderInfo.getBalance());

        if (userMapper.updateByPrimaryKey(userInfo) == 1) {
            //修改订单状态
            orderInfo.setStatus(1);
            if (orderMapper.updateByPrimaryKey(orderInfo) == 1) {
                return true;
            }
        }
        throw new CustomerException("订单支付失败!");
    }


}